package com.authine.cloudpivot.ext.controller.fileInfo.mainCom;

import com.authine.cloudpivot.engine.enums.status.SequenceStatus;
import com.authine.cloudpivot.engine.api.model.organization.UserModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectCreatedModel;
import com.authine.cloudpivot.engine.api.model.runtime.WorkItemModel;
import com.authine.cloudpivot.engine.api.model.runtime.WorkflowInstanceModel;

import com.authine.cloudpivot.ext.Utils.CustomSchemaCode;
import com.authine.cloudpivot.ext.service.CloudSqlService;
import com.authine.cloudpivot.web.api.controller.base.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 *  总公司级档案部门授权信息
 **/
@RestController
@RequestMapping("/public/mainCompanyDeptAuth")
@Slf4j
public class MainCompanyDeptAuthInfoController extends BaseController {



    @Autowired
    CloudSqlService sqlService;

    /**
     *  总公司级档案部门授权信息  审批流完成后 数据写到基础表-总公司级档案中间组织授权信息(总公司级档案部门授权信息)
     */
    @Async
//    @RequestMapping("empower")
    @RequestMapping("empower")
    public void empower(String bizId){
        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(CustomSchemaCode.MainCompanyDepartmentAuthInfo, bizId);

//        Object pushAllResult = bizObject.get("pushAllResult");


        List<Map<String, Object>> list = (List<Map<String, Object>>) bizObject.get("DepartmentAuthInfoSheet1");

        String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));


        //获取审批人
        String approvalType = (String) list.get(0).get("approvalType");
        String approval = getFileBaseInfoWorkFlowApproval(bizObject, approvalType);


        for (Map<String, Object> map : list) {
            String fileCode = (String) map.get("fileCode");

            try {

                //调用存储过程
                callProcess(map, approval);

            } catch (Exception e) {
                log.info("基础表-总公司档案下级公司  添加失败 fileCode={}", fileCode);
                log.info(e.getMessage(), e);
            }

        }
    }

    /**
     --------总公司级档案部门授权同步存储过程
     --------总公司级档案部门授权同步存储过程	----2023.03.22
     exec    SyncCorpArchiveComAuth
     @DEPTNUM     NVARCHAR(50),	----授权需求部门Num
     @Number	   nvarchar(100),	----档案代码
     @POSNUM      nvarchar(100),	----授权需求部门责任岗代码
     @RIGHT	   NVARCHAR(20),	----权限
     @Auditor     nvarchar(50)		----审批人  02.0033 李*

     */
    private void callProcess(Map<String, Object> map, String approval){

        if (ObjectUtils.isEmpty(map)) {
            return;
        }

        log.info("入参map={}", map);

        //调用存储过程
        String AType=MapUtils.getString(map, "archTypeYingshe","");// 档案类型
        String DEPTNUM = MapUtils.getString(map, "authDeptNumber", "");//授权需求部门
        String Number = MapUtils.getString(map, "fileCode", "");//档案代码
        String POSNUM = MapUtils.getString(map, "authReqDeptResPosNumber", "");//授权需求部门责任岗代码

        String purview = MapUtils.getString(map, "purview", "");//权限      1  五角    2  三角    3 √
        String RIGHT = "";
        purview = purview == null ? "" : purview;
        switch (purview) {
            case "★":
                RIGHT = "1";
                break;
            case "▲":
                RIGHT = "2";
                break;
            case "√":
                RIGHT = "3";
                break;
            case "空":
                RIGHT = "5";
                break;
        }

//        String execSql = String.format("exec [HG_LINK].[hg].[dbo].SyncCorpArchiveComAuth    '%s','%s','%s','%s','%s'",
//                DEPTNUM, Number, POSNUM, RIGHT,  approval);
                String execSql = String.format("exec [HG_LINK].[hg].[dbo].SyncArchiveComAuth    '%s','%s','%s','%s','%s','%s'",
                AType,DEPTNUM, Number, POSNUM, RIGHT,  approval);

        log.info("\n==========准备调用存储过程:{}", execSql);

        sqlService.execute(CloudSqlService.htEas, execSql);

        log.info("\n=============存储过程执行完成");

    }

    /**
     *  查询审批人,返回  员工号+姓名
     * @param bizObject
     * @param approvalType
     * @return
     */
    private String getFileBaseInfoWorkFlowApproval(BizObjectCreatedModel bizObject, String approvalType) {
        String mainDeptCode = (String) bizObject.get("mainDeptCode");
        String activityCode ="";
        if ("01".equals(approvalType)){
            String manageDeptCode = (String) bizObject.get("manageDeptCode");
            if (mainDeptCode.equals(manageDeptCode)){
                activityCode="Activity9";
            }else{
                activityCode="Activity14";

            }
        }else if("03".equals(approvalType)) {
            String frameDeptCode = (String) bizObject.get("frameDeptCode");
            if (mainDeptCode.equals(frameDeptCode)){
                activityCode="Activity26";
            }else{
                activityCode="Activity14";
            }
        }


        WorkflowInstanceModel instanceModel = getWorkflowInstanceFacade().getByObjectId(bizObject.getId());
        List<WorkItemModel> workItems = getWorkflowInstanceFacade().getWorkItems(instanceModel.getId(), true);
        final String finalActivityCode = activityCode;
        Optional<WorkItemModel> first = workItems.stream().filter(a -> a.getActivityCode().equals(finalActivityCode)).findFirst();
        String participant = null;
        if (first.isPresent()) {
            WorkItemModel workItemModel = first.get();
            participant = workItemModel.getParticipant();
        }

        if (participant == null) {
            participant = bizObject.getCreater().getId();
        }

        UserModel user = getOrganizationFacade().getUser(participant);


        return new StringBuilder(user.getEmployeeNo()).append(user.getName()).toString();
    }



    /**
     * 判断是否已存在
     * @param field
     * @param value
     * @param schemaCode
     * @return
     */
    private String existsBizObject(String field,String value,String schemaCode){

        String tableName = getBizObjectFacade().getTableName(schemaCode);

        StringBuilder sql = new StringBuilder("select id  from ").append(tableName)
                .append(" where ").append(field).append("='").append(value).append("'");

        Map<String, Object> map = sqlService.getMap(sql.toString());

        return (String) map.get("id");
    }

    /**
     *  转换成  基础表-总公司档案 的数据
     * @param map
     * @param auditDate
     * @return
     */
    private Map<String,Object> fileInfoBaseMap(Map<String,Object> map,String auditDate,String auditer){
        Map<String, Object> data = new HashMap<>();


        //关联档案
        data.put("relevFile",map.get("fileNumber"));
        //档案代码
        data.put("fileCode",map.get("fileCode"));
        //档案名称
        data.put("fileName",map.get("fileName"));

        //档案类型关联
        data.put("relevFileType",map.get("typeName"));
        //档案类型
        data.put("fileType",map.get("archTypeNumber"));
        //对应记录
        data.put("dyjl",map.get("record"));
        //关联基础代码
        data.put("relevBaseCode",map.get("basicCode"));
        //基础代码
        data.put("baseCode",map.get("baseCode"));
        //基础名称
        data.put("baseCodeName",map.get("name01"));
        //对应说明
        data.put("refDesc",map.get("refDes"));


        //关联管理部门
        data.put("manageFun",map.get("relevManageDept"));
        //管理部门代码
        data.put("manageDeptCode",map.get("manaDeptId"));
        //管理部门
        data.put("manageDeptName",map.get("manaDeptName"));


        //备注
        data.put("remark",map.get("remarks"));
        //电子版
        data.put("elec",map.get("elec"));
        //说明
        data.put("explains",map.get("des"));
        //职能关联
        data.put("fun",map.get("zn"));
        //职能代码
        data.put("funCode",map.get("znCode"));
        //职能
        data.put("funName",map.get("znName"));

        //主责部门代码
        data.put("mainDepartmentNumber",map.get("mainDepartmentNumber"));
        //主责部门
        data.put("mainDepartmentName",map.get("mainDepartmentName"));
        //关联公司主责部门
        data.put("MainDeptId",map.get("MainDeptId"));
        //主责公司主责部门
        data.put("defaultmainDeptId",map.get("defaultmainDeptId"));
        //主责部门
        data.put("MainDept",map.get("MainDept"));
        //关联公司主责岗
        data.put("mainPositionId",map.get("mainPositionId"));
        //公司主责岗代码
        data.put("mainPositionCode",map.get("mainPositionCode"));
        //公司主责岗
        data.put("mainPostionName",map.get("mainPostionName"));
        //上级权限
        data.put("superAuth",map.get("superAuth"));
        //上级组织责任岗代码
        data.put("supOrgResPosNumber",map.get("supOrgResPosNumber"));
        //上级组织责任岗
        data.put("supOrgResPosName",map.get("supOrgResPosName"));
        //关联授权需求部门责任岗
        data.put("authReqDeptResPosId",map.get("authReqDeptResPosId"));
        //授权需求部门责任岗代码隐藏
        data.put("authReqDeptResPosNumber",map.get("authReqDeptResPosNumber"));
        //授权需求部门责任岗
        data.put("authReqDeptResPosName",map.get("authReqDeptResPosName"));
        //部门授权
        data.put("purview",map.get("purview"));
        //纸质数量
//        data.put("paperNum",map.get(""));
        //01授权
//        data.put("one",map.get("1"));
        //02授权
//        data.put("two",map.get("1"));
        //03授权
//        data.put("three",map.get("1"));
        //04授权
//        data.put("four",map.get("1"));
        //05授权
//        data.put("five",map.get("1"));
        //06授权
//        data.put("six",map.get("1"));
        //07授权
//        data.put("seven",map.get("1"));
        //08授权
//        data.put("eight",map.get("1"));
        //09授权
//        data.put("nine",map.get("1"));
        //10授权
//        data.put("ten",map.get("1"));
        //工作说明
        data.put("jobDesc",map.get("refDes"));
        //审批时间
        data.put("auditDate",auditDate);
        //审批人
        data.put("auditer",auditer);


        return data;
    }
}
